<!-- 用户信息弹窗 -->
<script lang="ts" setup>
import { ref, computed } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import DuiForm from '@/common-ui/dui-form/index.vue'
import * as userApi from '@/api/user'
import * as roleApi from '@/api/role'
import * as orgApi from '@/api/org'
import type { IDbFormItem, IDbSelect } from '@/types/global'
import useNotic from '@/hooks/useNotic'
import type { IUserData } from '../config/type'
import { ENUM_SEX } from '@/config/enum'
import { SEX_LIST } from '@/config/list'
import { ENUM_USER_DISABLE, USER_DISABLE_LIST } from '../config'

const emits = defineEmits(['refresh'])

defineProps({
  // 标题
  title: {
    type: String,
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  }
})

// 详情id
const infoId = ref('')
// 弹窗表单数据
const ruleFormRef = ref<InstanceType<typeof DuiForm>>()
// 表单配置
const roleList = ref<IDbSelect[]>([])
const formConfig = computed<IDbFormItem[]>(() => {
  return [
    { label: '用户昵称', prop: 'nickName', type: 'input', required: true, span: 12 },
    { label: '手机号码', prop: 'phonenumber', type: 'input', required: true, span: 12 },
    { label: '电子邮箱', prop: 'email', type: 'input', required: true, span: 12 },
    { label: '用户名称', prop: 'userName', type: 'input', required: true, span: 12 },
    {
      label: '用户性别',
      prop: 'sex',
      type: 'radio',
      required: true,
      list: SEX_LIST,
      span: 12
    },
    {
      label: '用户状态',
      prop: 'status',
      type: 'radio',
      required: true,
      list: USER_DISABLE_LIST,
      span: 12
    },
    { label: '归属组织', prop: 'orgIds', type: 'slot', required: true, span: 24 },
    { label: '角色', prop: 'roleIds', type: 'select', list: roleList.value, options: { multiple: true }, span: 24 },
    { label: '身份证号', prop: 'idCard', type: 'input', span: 24 },
    { label: '备注', prop: 'remark', type: 'textarea' }
  ]
})
// 表单默认数据
const defaultData: IUserData = {
  nickName: '',
  orgIds: [],
  phonenumber: '',
  email: '',
  userName: '',
  sex: ENUM_SEX['男'],
  status: ENUM_USER_DISABLE['启用'],
  idCard: '',
  roleIds: [],
  remark: ''
}
// 表单数据
const formData = ref(JSON.parse(JSON.stringify(defaultData)))
// 是否显示弹窗
const showDialog = ref(false)

initData()

/**
 * 打开弹窗并初始化数据
 */
function init(id?: string) {
  // 详情-编辑
  infoId.value = id ?? ''
  if (id) {
    userApi.queryUser(id).then((res) => {
      if (res.success) {
        formData.value = {
          nickName: res.data.data.nickName,
          orgIds: res.data.orgs.map((item: any) => item.id),
          phonenumber: res.data.data.phonenumber,
          email: res.data.data.email,
          userName: res.data.data.userName,
          password: res.data.data.password,
          sex: res.data.data.sex,
          status: res.data.data.status,
          idCard: res.data.data.idCard,
          roleIds: res.data.roleIds,
          remark: res.data.data.remark
        }
      }
    })
  }
  // 添加
  else {
    formData.value = JSON.parse(JSON.stringify(defaultData))
  }
  showDialog.value = true
}

/**
 * 点击提交
 */
function submitClick() {
  ruleFormRef.value
    ?.validate()
    .then(() => {
      // 添加
      let reqFunc = userApi.addUser
      let params = formData.value
      // 修改
      if (infoId.value) {
        reqFunc = userApi.editUser
        params = { ...formData.value, userId: infoId.value }
      }
      reqFunc(params).then((res) => {
        if (res.success) {
          useNotic().success('提交成功！')
          showDialog.value = false
          emits('refresh')
        }
      })
    })
    .catch(() => {})
}

/**
 * 树节点加载事件
 */
function treeLoadEvt(node: Node, resolve: any) {
  let params = {}
  // 根节点加载
  if (node.level === 0) {
    params = { initOrg: 1 }
  }
  // 子节点加载
  else {
    params = { parentId: node.data.id }
  }
  setTimeout(() => {
    orgApi.getChildrenByOrgId(params).then((res) => {
      if (res.success) {
        const normalList = res.data.rows.map((item: any) => {
          return { ...item, value: item.id }
        })
        resolve(normalList)
      }
    })
  }, 500)
}

/**
 * 获取初始所需数据
 */
function initData() {
  // 获取角色列表
  roleApi.getRoleByPage({ pageNum: 1, pageSize: 99 }).then((res) => {
    if (res.success) {
      roleList.value = res.data.rows.map((item: any) => {
        return { label: item.roleName, value: item.roleId }
      })
    }
  })
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-form ref="ruleFormRef" :form-config="formConfig" :form-data="formData" :disabled="disabled">
      <template #orgIdsSlot>
        <el-tree-select
          style="width: 100%"
          v-model="formData.orgIds"
          multiple
          check-strictly
          lazy
          :load="treeLoadEvt"
          :props="{ label: 'orgName' }"
        />
      </template>
    </dui-form>
    <template #footer>
      <el-button @click="showDialog = false">关闭</el-button>
      <el-button type="primary" @click="submitClick" v-if="!disabled"> 确定 </el-button>
    </template>
  </dui-dialog>
</template>
